package com.sql.mysql.sharding.rewrite;

import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.merge.Merge;
import net.sf.jsqlparser.statement.replace.Replace;
import net.sf.jsqlparser.statement.update.Update;
import net.sf.jsqlparser.statement.upsert.Upsert;
import net.sf.jsqlparser.util.TablesNamesFinder;

@Slf4j
public class ReWriteTablesNamesFinder extends TablesNamesFinder {
	private String suffix;

	// 统一处理
	private void appendSuffix(Table table) {
		table.setName(table.getName() + suffix);
	}

	public ReWriteTablesNamesFinder(String s) {
		log.debug("set suffix {}", s);
		suffix = s;
	}

	@Override
	public void visit(Table tableName) {
		// 判断一下
		if (false == tableName.getName().endsWith(suffix)) {
			appendSuffix(tableName);
		}
		super.visit(tableName);
	}

	@Override
	public void visit(Delete delete) {
		appendSuffix(delete.getTable());
		super.visit(delete);
	}

	@Override
	public void visit(Update update) {
		for (Table table : update.getTables()) {
			appendSuffix(table);
		}
		super.visit(update);
	}

	@Override
	public void visit(Insert insert) {
		appendSuffix(insert.getTable());
		super.visit(insert);
	}

	@Override
	public void visit(Replace replace) {
		appendSuffix(replace.getTable());
		super.visit(replace);
	}

	@Override
	public void visit(CreateTable create) {
		appendSuffix(create.getTable());
		super.visit(create);
	}

	@Override
	public void visit(Merge merge) {
		appendSuffix(merge.getTable());
		super.visit(merge);
	}

	@Override
	public void visit(Upsert upsert) {
		appendSuffix(upsert.getTable());
		super.visit(upsert);
	}

}
